const util = require('../../../utils/util')
const validate = require('../../../utils/validate')
var { _get_store } = require('../../../utils/xiaohuangyu')
const app = getApp();

Page({
  onShareAppMessage() {
    return {
      title: 'editor',
      path: 'page/component/pages/editor/editor'
    }
  },
  data: {
    activityType: 'vote',   //活动类型
    activity_theme: [],   //活动类型
    stores: [],   //商铺信息
    stores_index: 0,
    activity_data: {
      activity_type: 1,
      title: '',
      store: -1,
      theme: -1,
      rules: "1. 点击我要参加进行报名。报名时候请在备注栏填写收货地址(如需要);\n2. 每个人只能砍价一次，自己不能给自己砍价;\n3. 砍到自己心仪的价格即可购买，活动以付款成功为准，砍到底价后请及时付款，避免商品售完造成无法购买;\n4. 如有问题请及时联系我们，详细联系方式见活动页面商家信息栏;\n5. 本次活动的优惠资格不可赠送或转让；活动解释权归本机构所有。\n\n\n\n\n",
      content: ''
    },
    bargain: {
      coupon_count: 0,
      old_price: 0,
      new_price: 0,
      min_bargain_count: 10,
      max_bargain_count: 20,
      valid_time: 1
    },
    vote: {
      vote_way: 2,
      vote_time: 1
    },
    imgList: [],
    imgIdList: [],
    startDateTime: {
      date: '2020-11-12',
      time: '08:12'
    },
    endDateTime: {
      date: '2020-11-12',
      time: '08:12'
    },
    navTabList: ['活动内容', '活动详情', '其他设置'],
    tabCur: 0,
    // 富文本属性
    formats: {},
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    safeHeight: 0,
    toolBarHeight: 50,
    activityContent: '',
  },
  onLoad(options) {
    // 初始化富文本数据
    this.initEditorData()
    // 初始化数据
    this.initData(options)
  },

  // 活动主题
  selectThemeTap(e) {
    this.setData({
      [`activity_data.theme`]: e.currentTarget.dataset.id
    })

  },
  // 开始时间
  stratDateChange(res) {
    this.setData({
      [`startDateTime.date`]: res.detail.value
    })
  },
  startTimeChange(res) {
    this.setData({
      [`startDateTime.time`]: res.detail.value
    })
  },
  // 结束时间
  endDateChange(res) {
    this.setData({
      [`endDateTime.date`]: res.detail.value
    })
  },
  endTimeChange(res) {
    this.setData({
      [`endDateTime.time`]: res.detail.value
    })
  },
  // 选择商铺
  storePickerChange(res) {
    console.log(this.data.stores[res.detail.value])
    this.setData({
      stores_index: res.detail.value,
      ['activity_data.store']: this.data.stores[res.detail.value].id
    })
  },
  // 标题
  bindTitleBlur(res) {
    this.setData({
      [`activity_data.title`]: res.detail.value
    })
  },
  // 富文本失去焦点
  editorBindblur(res) {
    this.setData({
      [`activity_data.content`]: res.detail.html
    })
  },
  // 初始化砍价次数范围
  initData(options) {
    // 设置标题
    wx.setNavigationBarTitle({
      title: options.title,
    })
    // 获取活动主题数据
    app.get('/member/system/dict/', {}, res => {
      console.log(res.data)
      this.setData({
        activity_theme: res.data.activity_theme,
        [`activity_data.theme`]: res.data.activity_theme[0].id  //默认第一个主题
      })
    })
    // 获取商铺信息
    _get_store(this.data.params, res => {
      if (res.data) {
        this.setData({
          stores: res.data.dataList,
          ['activity_data.store']: res.data.dataList[0].id  //默认第一个商铺
        })
      }
    })
    // 活动开始/结束时间设置
    // console.log(util.formatTheTime(new Date(Date.now())))

    var start_date = new Date()
    let activitystartDateTime = {
      date: util.formatTheDate(new Date(start_date.getTime())),
      time: util.formatTheTime(new Date(start_date.getTime()+60*60*1000)),
    }
    let activityendDateTime = {
      date: util.formatTheDate(new Date(start_date.setDate(start_date.getDate() + 5))),
      time: '23:59',
    }
    this.setData({
      activityType: options.type,   //活动类型
      startDateTime: activitystartDateTime,
      endDateTime: activityendDateTime,
      screenHeight: app.globalData.systemInfo.screenHeight,
      [`activity_data.activity_type`]: options.type === 'vote' ? 1 : 2
    })
  },
  // 初始化富文本数据
  /**  -----------初始化富文本数据--------------------- */
  initEditorData() {
    const { platform, safeArea, model, screenHeight } = wx.getSystemInfoSync()
    let safeHeight;
    if (safeArea) {
      safeHeight = (screenHeight - safeArea.bottom);
    } else {
      safeHeight = 32;
    }
    this._safeHeight = safeHeight;
    let isIOS = platform === 'ios'
    this.setData({ isIOS, safeHeight, toolBarHeight: isIOS ? safeHeight + 50 : 50 })
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) {
        return
      }
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)
    })
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    if (keyboardHeight === 0) {
      this.setData({
        editorHeight, keyboardHeight,
        toolBarHeight: this.data.isIOS ? 50 + this._safeHeight : 50,
        safeHeight: this._safeHeight,
      })
    } else {
      this.setData({
        editorHeight, keyboardHeight,
        toolBarHeight: 50,
        safeHeight: 0,
      })
    }
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        // 上传到服务器
        const tempFilePaths = res.tempFilePaths
        app.uploadFile(tempFilePaths[0], 'vote_image', reqs => {
          const result = JSON.parse(reqs)
          // 插入到富文本中
          that.editorCtx.insertImage({
            // 返回的地址路径
            src: result.data.url,
            data: {
              id: 'abcd',
              role: 'god'
            },
            width: '80%',
            success: function () {
              console.log(that.editorCtx)
            }
          })

        })
      }
    })
  },
  /**  -----------初始化富文本数据------end--------------- */
  // 导航条
  tabSelect(e) {
    this.setData({
      tabCur: e.currentTarget.dataset.id,
    })
  },
  // 上一步
  lastStepTap() {
    let tabCur = this.data.tabCur
    if (tabCur > 0) {
      this.setData({
        tabCur: tabCur - 1
      })
    }
  },
  // 下一步
  nextStepTap() {
    let tabCur = this.data.tabCur
    if (tabCur < this.data.navTabList.length - 1) {
      this.setData({
        tabCur: this.data.tabCur + 1
      })
    }
  },
  // 添加轮播图
  insertBannerImageTap() {
    var that = this
    let file_path = 'vote_image'
    if (that.data.activityType === 'bargain') {
      file_path = 'bargain_image'
    }
    wx.chooseImage({
      count: 4,
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success(res) {
        const tempFilePaths = res.tempFilePaths
        for (let i = 0; i < tempFilePaths.length; i++) {
          app.uploadFile(tempFilePaths[i], file_path, reqs => {
            const result = JSON.parse(reqs)
            that.setData({
              imgList: that.data.imgList.concat([tempFilePaths[i]]),
              imgIdList: that.data.imgIdList.concat([result.data.id])
            })
          })
        }
      }
    })
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除这张图片吗？',
      cancelText: '取消',
      confirmText: '确认',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.data.imgIdList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList,
            imgIdList: this.data.imgIdList
          })
        }
      }
    })
  },
  // 规则
  textareaAInputBlur(res) {
    this.setData({
      [`activity_data.rules`]: res.detail.value
    })
  },
  /**----------其他设置  砍价  start---------------- */
  // 优惠卷数量
  couponCountBlur(res) {
    this.setData({
      [`bargain.coupon_count`]: res.detail.params
    })
  },
  // 原价
  oldPriceBlur(res) {
    this.setData({
      [`bargain.old_price`]: res.detail.params
    })
  },
  // 低价
  newPriceBlur(res) {
    this.setData({
      [`bargain.new_price`]: res.detail.params
    })
  },
  // 砍价次数
  barginTimeChange(res) {
    this.setData({
      [`bargain.min_bargain_count`]: res.detail.params['min_bargain_count'],
      [`bargain.max_bargain_count`]: res.detail.params['max_bargain_count']
    })
  },
  validTimeChange(res) {
    this.setData({
      [`bargain.valid_time`]: res.detail.params['valid_time']
    })
  },
  /**----------其他设置  砍价  end---------------- */
  /**----------其他设置  投票  end---------------- */
  voteTimeChange(res) {
    this.setData({
      [`vote.vote_time`]: res.detail.params['vote_time'],
      [`vote.vote_way`]: res.detail.params['vote_way']
    })
  },
  /**----------其他设置  投票  end---------------- */
  validateParams(activity_data) {

    var now = new Date();
    var start_date = new Date(activity_data['start_time']);
    var end_date = new Date(activity_data['end_time']);
    if (start_date < now || end_date < start_date) {
      validate.showToast('活动时间设置有误，结束时间应该大于开始时间')
      return false
    }
    if (validate.isEmpty(activity_data['title'])) {
      validate.showToast('标题不能为空')
      return false
    }
    if (activity_data['theme'] < 0) {
      validate.showToast('请选择对应的活动主题')
      return false
    }
    if (activity_data['images'].length === 0) {
      validate.showToast('请至少上传一张图片')
      return false
    }
    if (validate.isEmpty(activity_data['content'])) {
      validate.showToast('活动详情不能为空')
      return false
    }

    if (this.data.activityType === 'bargain') {
      if (activity_data['bargain']['coupon_count'] < 1) {
        validate.showToast('请设置合格的优惠卷适量')
        return false
      }
      if (activity_data['bargain']['old_price'] < 0) {
        validate.showToast('请设置原价')
        return false
      }
      if (activity_data['bargain']['new_price'] < 0) {
        validate.showToast('请设置低价')
        return false
      }
    }

    return true
  },
  // 完成
  saveActivityTap() {
    let activity_data = this.data.activity_data
    activity_data['start_time'] = this.data.startDateTime['date'] + ' ' + this.data.startDateTime['time']
    activity_data['end_time'] = this.data.endDateTime['date'] + ' ' + this.data.endDateTime['time']
    activity_data['images'] = this.data.imgIdList
    activity_data['vote'] = this.data.vote
    activity_data['bargain'] = this.data.bargain
    console.log(activity_data)
    if (!this.validateParams(activity_data)) {
      return
    }
    app.post('/member/activity/', activity_data, res => {
      console.log(res)
    })
  },
})
